<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');?>
<?php $n_label = count($label); if($n_label > 0){?>
<div class="text-right">
	<a href="javascript:void(0);" onclick="exportDomain();" style="text-decoration:underline">
		Export PDF
	</a>
	&nbsp;&nbsp;|&nbsp;&nbsp;
	<a href="javascript:void(0);" onclick="exportDomain('excel');" style="text-decoration:underline">
		Export EXCEL
	</a>
	&nbsp;&nbsp;|&nbsp;&nbsp;
	<a href="javascript:void(0);" onclick="payPopup('panel-popup');" style="text-decoration:underline">
		Send Mail
	</a>
	&nbsp;&nbsp;|&nbsp;&nbsp;
	<a href="javascript:void(0);" onclick="domainConfigMail();" style="text-decoration:underline">
		Config Send Mail
	</a>
</div>

<div id="divConfigMail" class="martop10 pad5" style="background: #f9f9f9; display:none;">
	<table width="100%">
		<tr>
			<td class="pad5 text-right ver-middle" width="100">
				<b>Domain</b> <span class="require" style="color: red;">*</span>
			</td>
			<td class="pad5">
				<input class="input365" id="txtCfDomain" style="width: 800px;" />
			</td>
		</tr>
		<tr>
			<td class="pad5 text-right ver-middle" width="100">
				<b>Fullname</b> <span class="require" style="color: red;">*</span>
			</td>
			<td class="pad5">
				<input type="hidden" id="hddCfID" />
				<input class="input365" id="txtCfUserName" style="width: 800px;"/>
			</td>
		</tr>
		<tr>
			<td class="pad5 text-right" width="100">
				<b>Email</b> <span class="require" style="color: red;">*</span>
			</td>
			<td class="pad5">
				<textarea id="txtEmail" name="txtEmail" class="pad5" style="width: 800px; height: 80px;"></textarea>
			</td>
		</tr>
		
		<tr>
			<td class="pad5 text-right ver-middle" width="100">
				<b>Current domain</b>
			</td>
			<td class="pad5">
				<p id="currDoamain"></p>
			</td>
		</tr>
		
		<tr>
			<td class="pad5 text-right" width="100">
				<b>Message</b>
			</td>
			<td class="pad5">
				<textarea id="txtCfMess" name="txtCfMess" class="pad5" style="width: 800px; height: 100px;"></textarea>
			</td>
		</tr>
		
		<tr>
			<td class="pad5 text-right ver-middle" width="100">
				&nbsp;
			</td>
			<td class="pad5">
				<input type="button" class="button" value="Set Config" onclick="setConfigDomainEmail();" />
				<img alt="" src="/admin/images/ajaxLoading.gif" id="scfLoading" style="display: none; margin-left: 10px;" />
			</td>
		</tr>
		
	</table>
	<br />
	<p>
		Cấu hình hiện tại &nbsp;&nbsp;&nbsp;&nbsp;<input type="button" value="Show/Hide" onclick="$('#divCurrDCE').toggle();" />
	</p>
	<div id="divCurrDCE">
		<table width="100%" class="tbl-list martop10" cellpadding="0" cellspacing="0" border="0">
			<tr>
				<td class="td-label bold text-center" width="50">
					ID
				</td>
				<td class="td-label bold">
					Username
				</td>
				<td class="td-label bold">
					Email
				</td>
				<td class="td-label bold">
					List domain
				</td>
				<td class="td-label bold" width="90">
					Last send time
				</td>
				<td class="td-label bold text-center" width="50">
					Actions
				</td>
			</tr>
			<?php
			foreach($lstCurrConfig as $cuser)
			{
			?>
				<tr class="lst-item">
					<td class="pad5 text-center">
						<?php echo $cuser['cfid']; ?>
					</td>
					<td class="pad5">
						<a href="javascript:void(0);" onclick="dmcf_search_select_user('<?php echo $cuser['cfid']; ?>');">
							<?php echo $cuser['fullname']; ?>
						</a>
					</td>
					<td class="pad5">
						<a href="javascript:void(0);" onclick="dmcf_search_select_user('<?php echo $cuser['cfid']; ?>');">
							<?php echo $cuser['email']; ?>
						</a>
					</td>
					<td class="pad5">
						<?php echo $cuser['report_domain']; ?>
					</td>
					<td class="pad5">
						<?php echo $cuser['reported_time']; ?>
					</td>
					<td class="pad5 text-center">
						<img src="/admin/images/delete_icon.png" width="16" class="cursor-pointer" onclick="dmcf_delete('<?php echo $cuser['cfid']; ?>');" />
					</td>
				</tr>
			<?php
			}
			?>
		</table>
	</div>
	
	<script type="text/javascript">
		function dmcf_get_list()
		{
			var onSuccess = function(data)
			{
				$('#cfLoading').hide();
				$('#divCurrDCE').html(data);
			};
			var onError = function()
			{
				$('#cfLoading').hide();
				$('#divCurrDCE').html('Error').show();
			};
			$('#cfLoading').show();
			var url = '<?php echo site_url('report/ajax_domain_report_config_list');?>';
			getAjax(url, '', '', '', '', false, onSuccess, onError);
		}
		
		function dmcf_delete(cfid)
		{
			var onSuccess = function(data)
			{
				$('#cfLoading').hide();
				var obj = jQuery.parseJSON(data);
				if(obj.r == '0' || obj.r == '2')
				{
					window.location.reload(true);
					return;
				}
				else if(obj.r == '1')
				{
					alert('Xóa thành công.');
					dmcf_get_list();
					return;
				}
				
			};
			var onError = function()
			{
				$('#cfLoading').hide();
			};
			if(confirm('Bạn có thật sự muốn xóa?'))
			{
				$('#cfLoading').show();	
				var url = '<?php echo site_url('report/delete_config_domain_email');?>';
				getAjax(url, 'cfid=' + cfid, '', '', '', false, onSuccess, onError);
			}
			else
			{
				return;
			}
		}
		
		function setConfigDomainEmail()
		{
			var cfid = $.trim($('#hddCfID').val());
			var domain = $.trim($('#txtCfDomain').val());
			var fullname = $.trim($('#txtCfUserName').val());
			var email = $.trim($('#txtEmail').val());
			var mess = $.trim($('#txtCfMess').val());
			
			if(domain != '' && fullname != '' && email != '')
			{
				var onSuccess = function(data)
				{
					$('#cfLoading').hide();
					var obj = jQuery.parseJSON(data);
					if(obj.r == '0')
					{
						window.location.reload(true);
						return;
					}
					else if( obj.r == '2')
					{
						alert('Bạn không có quyền');
						return;
					}
					else if(obj.r == '1')
					{
						$('#currDoamain').html('');
						$('#txtCfUserName').val('');
						$('#hddCfID').val('');
						$('#txtCfDomain').val('');
						$('#txtEmail').val('');
						$('#txtCfMess').val('');
						dmcf_get_list();
						alert('Cập nhật thành công');
						return;
					}
				};
				var onError = function()
				{
					$('#cfLoading').hide();
				};
				$('#cfLoading').show();	
				var url = '<?php echo site_url('report/set_config_domain_email');?>';
				getAjax(url, 'cfid=' + cfid + '&d=' + UrlEncode.encode(domain) + '&fn=' + UrlEncode.encode(fullname) + '&m=' + UrlEncode.encode(email) + '&mess=' + UrlEncode.encode(mess), '', 'POST', '', false, onSuccess, onError);
			}
			else
			{
				alert('Kiểm tra lại dữ liệu nhập.');
				return;
			}
		}
		
	
		function dmcf_search_select_user(cfid)
		{
			$('#hddCfID').val(cfid);
			var onSuccess = function(data)
			{
				$('#cfLoading').hide();
				var obj = jQuery.parseJSON(data);
				if(obj.r == '0' || obj.r == '2')
				{
					window.location.reload(true);
					return;
				}
				else if(obj.r == '1')
				{
					$('#currDoamain').html(obj.report_domain);
					$('#txtCfDomain').val(obj.report_domain);
					$('#txtCfUserName').val(obj.username);
					$('#txtEmail').val(obj.email);
					$('#txtCfMess').val(obj.mess);
					return;
				}
				
			};
			var onError = function()
			{
				$('#cfLoading').hide();
			};
			$('#cfLoading').show();	
			var url = '<?php echo site_url('report/ajax_domain_config_user');?>' + '/' + cfid;
			getAjax(url, '', '', '', '', false, onSuccess, onError);
		}
	</script>
</div>

<br />
<form name="frmSendMail" action="" method="post" onsubmit="return false;">
<div style="overflow-x:scroll;">
    <table width="100%" cellspacing="0" cellpadding="0" border="0" id="table" class="martop5 tbl-list tablesorter">
        <thead>
        <tr>
        	<th class="td-label bold text-center" width="20">
                Stt
            </th>
            <th class="td-label bold">
           		<input type="checkbox" id="cbAll" onclick="checkOnOff(this.checked);" />
            </th>
        	<?php foreach ($label as $title){?>
            <th class="td-label bold">
           		<?php echo $title;?>
           		<?php if(strtolower($title) == 'clickfromad'){?>
           		[<b onclick="toannh_tooltip(this, '<?php echo $title;?>', 'Đây là số Click tính tiền xuất phát từ các banner của Khách hàng mua CPC');" >?</b>]
           		<?php } else if(strtolower($title) == 'viewfromad'){?>
           		[<b onclick="toannh_tooltip(this, '<?php echo $title;?>', 'Đây là số Impressions xuất phát từ các banner của Khách hàng mua CPC');" >?</b>]
           		<?php } else if(strtolower($title) == 'totalcpm4k'){?>
           		[<b onclick="toannh_tooltip(this, '<?php echo $title;?>', 'Đây là số CPM tính tiền xuất phát từ các banner của KH mua CPM 4k');" >?</b>]
           		<?php } else if(strtolower($title) == 'totalclick'){?>
           		[<b onclick="toannh_tooltip(this, '<?php echo $title;?>', 'Đây là tổng số Click của toàn hệ thống (AdMarket, 4k)');" >?</b>]
           		<?php } else if(strtolower($title) == 'totalview'){?>
           		<br>[<b onclick="toannh_tooltip(this, '<?php echo $title;?>', 'Đây là tổng số Impresssions của toàn hệ thống (AdMarket, 4k)');" >?</b>]
           		<?php } else if(strtolower($title) == 'cpcshared'){?>
           		[<b onclick="toannh_tooltip(this, '<?php echo $title;?>', 'Số tiền CPC tạm tính cho website (=60% của ClickFromAd*Giá CPC)');" >?</b>]
           		<?php } else if(strtolower($title) == 'cpmshared'){?>
           		[<b onclick="toannh_tooltip(this, '<?php echo $title;?>', 'Số tiền CPM tạm tính cho website (=60% của totalCPM4k*Giá CPM4k)');" >?</b>]
           		<?php } else if(strtolower($title) == 'moneyshared'){?>
           		[<b onclick="toannh_tooltip(this, '<?php echo $title;?>', 'Là tổng số tiền tạm tính cho website (=số CPCShared + CPMShared)');" >?</b>]
           		<?php } else if(strtolower($title) == 'inventoryshared(%)'){?>
           		[<b onclick="toannh_tooltip(this, '<?php echo $title;?>', '= Tỉ lệ 100%*ViewFromAd/totalview. Tỉ lệ này càng cao phản ánh banner của KH chiếm đa số, ngược lại banner nội bộ chiếm đa số');" >?</b>]
           		<?php }?>
            </th>
            <?php }?>
        </tr>
        </thead>
        <tbody>
        <?php $i = 0; foreach ($items as $item){ $i++;?>
        <tr class="row">
        	<td class="text-center">
        		<?php echo $i;?>
        	</td>
        	<td>
            	<input type="checkbox" name="sendRow[]" value="<?php echo $item->$label[0];?>" class="cbItems" onclick="checkDoaminItem();" />
            </td>
        	<?php $ii = 0; foreach ($label as $title){
        		$ii++;
        		if(is_numeric($item->$title) && strpos($title, '(%)') === false) $labelTotal[$title] += $item->$title;
        	?>
            <td class="<?php if(is_numeric($item->$title)) echo 'text-right';?>">
           		<?php
           		if($title == 'domain'){
           		?>
           		<a href="javascript:void(0);" onclick="adDomainFilter('<?php echo $item->$title;?>');"><?php echo $item->$title;?></a>
           		<?php } else echo (is_numeric($item->$title) && $n_label > $ii ? number_format($item->$title) : $item->$title);
           		?>
            </td>
            <?php }?>
        </tr>
        <?php }?>
        </tbody>
        <tfoot>
        <tr>
    		<td colspan="2" class="td-label bold text-right">Tổng:</td>
    		<?php foreach ($label as $title){?>
            <td class="td-label bold text-right">
           	<?php echo is_numeric($labelTotal[$title]) ? number_format($labelTotal[$title]) : $labelTotal[$title];?>
            </td>
            <?php }?>
    	</tr>
    	</tfoot>
    </table>
    </div>
    <div id="panel-popup" style="width: 360px">
    	<div style="background:#fff; padding:20px 10px; position:relative">
    	<span class="pay-mess"></span>
    	<table width="100%" style="border-spacing:3px;">
    		<tr>
    			<td colspan="2">
    				<span class="order-title">Email</span><br /><br />
    			</td>
    		</tr>
    		<tr>
    			<td width="50">To:</td>
    			<td><input type="text" name="mailTo" size="40" /></td>
    		</tr>
    		<tr>
    			<td>Cc:</td>
    			<td><input type="text" name="mailCc" size="40" /></td>
    		</tr>
    		<tr>
    			<td>Bcc:</td>
    			<td><input type="text" name="mailBcc" size="40" /></td>
    		</tr>
    		<tr>
    			<td>Message:</td>
    			<td><textarea name="mailMess" style="width: 260px;height: 80px"></textarea></td>
    		</tr>
    		<tr>
    			<td colspan="2" style="font-size:11px; color: #888">
    				Chú ý: gửi cho nhiều email, các email phân cách bởi dấu phẩy (,).
    			</td>
    		</tr>
    		<tr>
    			<td>&nbsp;</td>
    			<td class="text-right">
    				<br />
    				<input type="button" value="Send" onclick="ajaxSendMail();" />
    				<input type="reset" value="Cancel" onclick="closePopup();" />
	    			</td>
    		</tr>
	    	</table>
	    	<img src="/images/ajaxLoading.gif" id="loading-order" />
    	</div>
    </div>
</form>
<div id="toannh-tooltip" >
	<p class="myclear">
		<img alt="" id="toannh-tooltip-arrow" src="/images/toannhtooltiparrow.gif" />
	</p>
	<div id="toannh-tooltip-inner" >
		<p id="toannh-tooltip-title"></p>
		<div id="toannh-tooltip-body" class="myclear"></div>
		<p class="ok-box myclear">
			<img alt="" src="/images/okbtn.gif" onclick="removeToannh_Tooltip();" />
		</p>
	</div>
</div>
<div style="clear:both; height:10px;"><span></span></div>
<div id="charDomainClick1" class="chart"></div>
<script type="text/javascript">
    function domainConfigMail()
    {
    	$('#divConfigMail').toggle();
    }
	
	$(function(){
		$('.tbl-list .row').mouseover(function(){
			$(this).css('background','#ffc');
		});
		$('.tbl-list .row').mouseout(function(){
			$(this).css('background','none');
		});

        $('.tablesorter').tablesorter({textExtraction: function(node){
	        	var val = node.innerHTML;
	        	val = val.replace(/,/g, '');
	        	return val;
        	},
        	sortList: [[0,0]],
        	sortMultiSortKey: 'ctrlKey',
        	headers: {
            	1: {sorter: false}
            }
        });
	});
	function exportDomain(type)
	{
		if(typeof(type) === 'undefined' || type == '') type = 'pdf';
		var url = '<?php echo site_url('report/domain/?fromdate='.$fromdate.'&todate='.$todate);?>&export=' + type;
		window.location.href = url;
	}
	function checkOnOff(val)
	{
		$('.cbItems').attr('checked', val);
		if(val)
		{
			var arr = $('#table .cbItems');
			var str = '';
			jQuery.each(arr, function()
			{
				str += (str != '') ? ', ' + $(this).val() : $(this).val();
			});
			$('#txtCfDomain').val(str);
		}
		else
		{
			$('#txtCfDomain').val('');
		}
	}
	
	function checkDoaminItem()
	{
		var arr = $('#table .cbItems');
		var str = '';
		var chk = true;
		jQuery.each(arr, function()
		{
			if($(this).attr('checked'))
			{
				str += (str != '') ? ', ' + $(this).val() : $(this).val();
			}
			else
			{
				chk = false;
			}
		});
		$('#txtCfDomain').val(str);
		$('#cbAll').attr('checked', chk);
	}
	
	function closePopup()
	{
		$('#panel-popup, #mask').hide();
		$('#panel-popup .pay-mess').html('');
	}
	function checkEmailList(str)
	{
		var arrEmail = str.split(",");
		for (item in arrEmail)
		{
			if(arrEmail[item].trim() != '' && validateEmail(arrEmail[item].trim()) != '')
			{
				return false;
			}
		}
		return true;
	}
	function ajaxSendMail()
	{
		var err = $('#panel-popup .pay-mess');
		var items = $('input:checkbox[name="sendRow[]"]:checked');
		var mailTo = $('input:text[name="mailTo"]');
		var mailCc = $('input:text[name="mailCc"]').val();
		var mailBcc = $('input:text[name="mailBcc"]').val();
		if($(items).length == 0)
		{
			$(err).html('Hãy chọn các bản ghi muốn gửi.'); return false;
		}
		if($(mailTo).val() == '')
		{
			$(err).html('Hãy nhập Email người nhận.'); return false;
		}
		else	//Kiem tra cac email co hop le khong
		{
			if (!checkEmailList($(mailTo).val())
				|| (mailCc != '' && !checkEmailList(mailCc))
				|| (mailBcc != '' && !checkEmailList(mailBcc))
			)
			{
				$(err).html('Địa chỉ Email không hợp lệ.'); return false;
			}
		}

		//Process sendmail
		var img = $('#loading-order'); $(img).show();
		var domain = new Array($(items).length);
		var loop = 0;
		var mailMess = $('textarea[name="mailMess"]').val();
		mailTo = $(mailTo).val();
		var fromdate = '<?php echo $fromdate;?>';
		var todate = '<?php echo $todate;?>';
		
		$(items).each(function(){
			domain[loop] = $(this).val();
			loop++;
		});
		$.ajax({
			url: '<?php echo site_url('report/sendReportDomain');?>',
			type: 'post',
			data: {mailTo:mailTo, mailCc:mailCc, mailBcc:mailBcc, sendRow:domain, mailMess:mailMess, fromdate:fromdate, todate:todate},
			success: function(data){
				$(img).hide();
				if(data == '1')
				{
					$(err).html('Đã thành công!');
					setTimeout("closePopup();", 3000);
				}
				else
				{
					$(err).html('Không thành công, bạn hãy thử lại.');
				}
			}
		});
	}

	var addCommasNumber=function addCommas(nStr)
    {
    	nStr += '';
    	x = nStr.split('.');
    	x1 = x[0];
    	x2 = x.length > 1 ? '.' + x[1] : '';
    	var rgx = /(\d+)(\d{3})/;
    	while (rgx.test(x1)) {
    		x1 = x1.replace(rgx, '$1' + ',' + '$2');
    	}
    	return x1 + x2;
    }

    var chart1 = new Highcharts.Chart({
        chart: {
           renderTo: 'charDomainClick1',
           defaultSeriesType: 'spline'
        },
        title: {
           text: 'Thống kê clickfromAd & totalClick (từ <?php echo date('d/m/Y', strtotime($fromdate));?> đến <?php echo date('d/m/Y', strtotime($todate));?>)'
        },
        subtitle: {
           text: ''
        },
        xAxis: {
           categories: ['<?php echo implode("','", $xNameArr);?>'],
           tickInterval: <?php $step = (int)(count($xNameArr)/4); echo ($step > 0 ? $step : 1);?>,
  		     gridLineWidth: 0
  	      },
  	      yAxis: {
  	         title: {
  	            text: 'Số lượng click'
  	         },
  	         labels: {
  	            formatter: function() {
  	               return addCommasNumber(this.value)
  	            }
  	         },
  	         min: 0
  	      },
  	      tooltip: {
  	         crosshairs: true,
  	         shared: true,
    	     formatter: function()
  	         {
  	             var s = '<b>Ngày '+ this.x +'</b>';
  	             $.each(this.points, function(i, point) {
  	                 s += '<br/>'+ point.series.name +': '+addCommasNumber(point.y);
  	             });
  	             return s;
  	         }
  	      },
  	      plotOptions: {
              spline: {
                 marker: {
                    enable: false
                 }
              }
           },
  	      series: [{
  	         name: 'totalClick',
  	         data: [<?php echo implode(',', $totalClickArr);?>]
        },
        {
	         name: 'clickfromAd',
	         data: [<?php echo implode(',', $clickArr);?>]
      	}],
        exporting: {
            enabled: false
        }
     });
</script>
<?php }?>
